/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset;

import java.sql.Timestamp;
import java.util.*;

import nfse.NetFSERecord;
import nfse.NetFSEUtil;
import nfse.gui.record.FlexRecord;
import nfse.gui.record.FlexRecordField;

/*******************************************************************************
 * This is a generic catch-all class for free-form syslog data. It is used to
 * assess new data types for inclusion in Net/FSE or in cases where the data
 * does not contain indexable information like IPs and ports.
 * 
 * @author bduphoff
 * 
 */
public class SyslogRecord extends NetFSERecord {

    /***************************************************************************
     * The text data of the syslog message.
     */
    private String data = "";

    public String createMergeTableSQL(String table, String[] tableNames) {
        StringBuffer temp = new StringBuffer("create table ");
        temp.append(table);
        temp.append("(");
        temp.append("srcip bigint");
        temp.append(",");
        temp.append("startts datetime");
        temp.append(",");
        temp.append("record blob");
        temp.append(",");
        temp.append("record_hex blob");
        temp.append(") ENGINE=MERGE UNION (");
        for (int i = 0; i < tableNames.length; i++) {
            if (i > 0)
                temp.append(",");
            temp.append(tableNames[i]);
        }
        temp.append(") INSERT_METHOD=LAST");
        // System.out.println(temp.toString());
        return temp.toString();
    }

    /***************************************************************************
     * SyslogRecords can be parsed in two forms: raw and altered. Raw records
     * are original syslog messages. Altered logs are those that have been
     * processed by Net/FSE in the past. Altered records contain a timestamp and
     * an optional source IP address followed by the original raw syslog
     * message. The three fields are delimited by semicolons.
     */
    public NetFSERecord generate(String line, int sensor) throws Exception {
        SyslogRecord rec = new SyslogRecord();
        rec.setTypeID(typeID);
        rec.setSensorID(sensor);

        /***********************************************************************
         * Find the offsets of the first two ':'s relative to the first ':',
         * which indicates the end of the syslog header.
         */
        int idx1 = line.indexOf(";");
        int idx2 = line.indexOf(";", idx1 + 2);
        int colIdx = line.indexOf(":");

        /***********************************************************************
         * If the first two ';' indexes are before the first ':' then this is an
         * altered syslog message. If not, then the syslog record is "raw".
         */
        if (idx1 == -1 || (idx1 != -1 && colIdx < idx1)) {
            // Process a raw syslog message
            rec = new SyslogRecord();
            StringTokenizer st = new StringTokenizer(line);
            rec = new SyslogRecord();
            rec.setTimestamp(NetFSEUtil.timestampFromSyslog(line));
            boolean done = false;
            while (!done) {
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    try {
                        rec.setSrcIP(NetFSEUtil.convertIPtoLong(token));
                        done = true;
                    } catch (Exception e) {

                    }
                } else {
                    done = true;
                }
            }

            if (rec.getSrcIP() == -1)
                return null;
            rec.data = line;
            rec.setInitialString(rec.getTimestamp().getTime() / 1000 + ";" + rec.getSrcAddr() + ";" + line);
        } else {
            // Process an altered syslog message

            if (idx2 == -1) {
                // If the log fails this sanity check it is corrupted
                return null;
            }

            rec = new SyslogRecord();
            long tsLong = Long.parseLong(line.substring(0, idx1));
            if (tsLong == -1) {
                // If no timestamp is present use now as the timestamp
                rec.setTimestamp(NetFSEUtil.timestampFromSyslog(line));
                line = rec.getTimestamp().getTime() / 1000 + line.substring(idx1);
                idx1 = line.indexOf(";");
                idx2 = line.indexOf(";", idx1 + 2);
                colIdx = line.indexOf(":");
                // System.out.println("Try again: " + idx1 + ", " + idx2 + ", "
                // + colIdx);

            } else {
                // Parse the integer value into a SQL timestamp
                rec.setTimestamp(new Timestamp(tsLong * 1000));
            }

            // System.out.println(line.substring(idx1 + 1, idx2));
            rec.setSrcIP(NetFSEUtil.convertIPtoLong(line.substring(idx1 + 1, idx2)));
            rec.data = line.substring(idx2 + 1);
            rec.setSensorID(sensor);
            rec.setInitialString(line);
        }
        return (NetFSERecord) rec;
    }

    public String getCreateFieldTableSQL(String table) {
        StringBuffer temp = new StringBuffer("create table " + table + " (ID bigint, ");
        temp.append("srcip inet,");
        temp.append("startts timestamp,");
        temp.append("data text");
        temp.append(")");
        return temp.toString();
    }

    public FlexRecord getFlexRecord() {
        FlexRecord temp = new FlexRecord();
        temp.values = new String[3];
        int idx = -1;
        temp.values[++idx] = this.getTimestamp().toString();
        temp.values[++idx] = this.getSrcAddr();
        temp.values[++idx] = this.data;
        return temp;
    }

    public FlexRecordField[] getFlexRecordFields() {
        FlexRecordField[] temp = new FlexRecordField[3];
        int idx = -1;
        temp[++idx] = new FlexRecordField("Start Time", "startts", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_TIMESTAMP);
        temp[++idx] = new FlexRecordField("Src IP", "srcip", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_IP_ADDR);
        temp[++idx] = new FlexRecordField("Data", "data", FlexRecordField.TYPE_STRING, FlexRecordField.SUB_TYPE_NONE);
        return temp;
    }

    public String getInsertFieldTableSQL(int id, String table) {
        StringBuffer temp = new StringBuffer("insert into " + table + " values (" + id + ",'");
        temp.append(this.getSrcAddr() + "',");
        temp.append("'" + this.getStartTS() + "',");
        temp.append("'" + this.data + "'");
        temp.append(")");
        System.out.println(temp.toString());
        return temp.toString();
    }

    public Timestamp getStartTS() {
        return getTimestamp();
    }

    public String getTypeName() {
        return "Syslog";
    }

    public String toCSV() {
        return this.getTimestamp() + "," + getSrcIP() + "," + getSrcAddr() + "," + data;
    }

    public boolean isSyslog() {
        return true;
    }

	/**
	 * @param data the data to set
	 */
	public void setData(String data) {
		this.data = data;
	}

	/**
	 * @return the data
	 */
	public String getData() {
		return data;
	}

}
